package com.example.pdftomarkdown.service;

import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;

/**
 * PDF转Word服务类
 * 负责将PDF文件转换为Word文档格式
 */
@Service
public class PdfToWordConverterService {
    
    @Autowired
    private PdfParserService pdfParserService;
    
    private static final Pattern TITLE_PATTERN = Pattern.compile("^(第[一二三四五六七八九十\\d]+章|Chapter\\s+\\d+|\\d+\\.|#{1,6}\\s+).*");
    private static final Pattern SUBTITLE_PATTERN = Pattern.compile("^(\\d+\\.\\d+|[一二三四五六七八九十]+、).*");
    
    /**
     * 将PDF文件转换为Word文档
     * 
     * @param file 上传的PDF文件
     * @return Word文档的字节数组
     * @throws IOException 文件处理异常
     */
    public byte[] convertPdfToWord(MultipartFile file) throws IOException {
        if (file.isEmpty()) {
            throw new IllegalArgumentException("上传的文件不能为空");
        }
        
        if (!isPdfFile(file)) {
            throw new IllegalArgumentException("只支持PDF格式文件");
        }
        
        // 提取PDF文本内容
        String pdfText = pdfParserService.extractTextFromPdf(file);
        
        // 创建Word文档
        return createWordDocument(pdfText, file.getOriginalFilename());
    }
    
    /**
     * 创建Word文档
     * 
     * @param content PDF提取的内容
     * @param originalFilename 原始文件名
     * @return Word文档字节数组
     * @throws IOException 文档创建异常
     */
    private byte[] createWordDocument(String content, String originalFilename) throws IOException {
        XWPFDocument document = new XWPFDocument();
        
        try {
            // 添加文档标题
            addDocumentTitle(document, originalFilename);
            
            // 处理文档内容
            processContent(document, content);
            
            // 转换为字节数组
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            document.write(outputStream);
            return outputStream.toByteArray();
            
        } finally {
            document.close();
        }
    }
    
    /**
     * 添加文档标题
     */
    private void addDocumentTitle(XWPFDocument document, String filename) {
        XWPFParagraph titleParagraph = document.createParagraph();
        titleParagraph.setStyle("Title");
        
        XWPFRun titleRun = titleParagraph.createRun();
        String title = extractTitleFromFilename(filename);
        titleRun.setText(title);
        titleRun.setBold(true);
        titleRun.setFontSize(18);
        titleRun.setFontFamily("宋体");
        
        // 添加空行
        document.createParagraph();
    }
    
    /**
     * 处理文档内容
     */
    private void processContent(XWPFDocument document, String content) {
        if (content == null || content.trim().isEmpty()) {
            XWPFParagraph paragraph = document.createParagraph();
            XWPFRun run = paragraph.createRun();
            run.setText("注意：该PDF文件未能提取到有效文本内容。");
            run.setColor("FF0000"); // 红色
            return;
        }
        
        String[] paragraphs = content.split("\\n\\n+");
        
        for (String paragraph : paragraphs) {
            paragraph = paragraph.trim();
            if (paragraph.isEmpty()) {
                continue;
            }
            
            // 处理页面分隔符
            if ("---".equals(paragraph)) {
                addPageBreak(document);
                continue;
            }
            
            // 处理不同类型的内容
            if (isTitle(paragraph)) {
                addTitle(document, paragraph);
            } else if (isSubtitle(paragraph)) {
                addSubtitle(document, paragraph);
            } else if (isList(paragraph)) {
                addList(document, paragraph);
            } else {
                addNormalParagraph(document, paragraph);
            }
        }
    }
    
    /**
     * 判断是否为标题
     */
    private boolean isTitle(String text) {
        return TITLE_PATTERN.matcher(text).matches() || 
               text.startsWith("###") || 
               text.startsWith("##") || 
               text.startsWith("#");
    }
    
    /**
     * 判断是否为副标题
     */
    private boolean isSubtitle(String text) {
        return SUBTITLE_PATTERN.matcher(text).matches() ||
               text.startsWith("####");
    }
    
    /**
     * 判断是否为列表
     */
    private boolean isList(String text) {
        return text.startsWith("•") || 
               text.startsWith("-") || 
               text.startsWith("*") ||
               text.matches("^\\d+\\.\\s+.*");
    }
    
    /**
     * 添加标题
     */
    private void addTitle(XWPFParagraph paragraph, String text) {
        // 清理标题标记
        text = text.replaceAll("^#{1,6}\\s*", "").trim();
        
        XWPFRun run = paragraph.createRun();
        run.setText(text);
        run.setBold(true);
        run.setFontSize(16);
        run.setFontFamily("黑体");
        
        // 添加空行
        paragraph.getDocument().createParagraph();
    }
    
    /**
     * 添加标题（重载方法）
     */
    private void addTitle(XWPFDocument document, String text) {
        XWPFParagraph paragraph = document.createParagraph();
        addTitle(paragraph, text);
    }
    
    /**
     * 添加副标题
     */
    private void addSubtitle(XWPFDocument document, String text) {
        XWPFParagraph paragraph = document.createParagraph();
        XWPFRun run = paragraph.createRun();
        run.setText(text);
        run.setBold(true);
        run.setFontSize(14);
        run.setFontFamily("黑体");
    }
    
    /**
     * 添加列表
     */
    private void addList(XWPFDocument document, String text) {
        String[] lines = text.split("\\n");
        
        for (String line : lines) {
            line = line.trim();
            if (line.isEmpty()) continue;
            
            XWPFParagraph paragraph = document.createParagraph();
            XWPFRun run = paragraph.createRun();
            
            // 处理列表项符号
            if (line.startsWith("•") || line.startsWith("-") || line.startsWith("*")) {
                line = "● " + line.substring(1).trim();
            } else if (line.matches("^\\d+\\.\\s+.*")) {
                // 保持编号格式不变
            }
            
            run.setText(line);
            run.setFontFamily("宋体");
            
            // 设置缩进
            paragraph.setIndentationLeft(400);
        }
    }
    
    /**
     * 添加普通段落
     */
    private void addNormalParagraph(XWPFDocument document, String text) {
        String[] lines = text.split("\\n");
        
        for (String line : lines) {
            line = line.trim();
            if (line.isEmpty()) continue;
            
            XWPFParagraph paragraph = document.createParagraph();
            XWPFRun run = paragraph.createRun();
            run.setText(line);
            run.setFontFamily("宋体");
            run.setFontSize(12);
            
            // 设置段落间距
            paragraph.setSpacingAfter(120);
        }
    }
    
    /**
     * 添加分页符
     */
    private void addPageBreak(XWPFDocument document) {
        XWPFParagraph paragraph = document.createParagraph();
        XWPFRun run = paragraph.createRun();
        run.addBreak(org.apache.poi.xwpf.usermodel.BreakType.PAGE);
    }
    
    /**
     * 从文件名提取标题
     */
    private String extractTitleFromFilename(String filename) {
        if (filename == null || filename.trim().isEmpty()) {
            return "PDF转Word文档";
        }
        
        // 移除文件扩展名
        String title = filename.replaceAll("\\.[pP][dD][fF]$", "");
        
        // 处理常见的文件名格式
        title = title.replaceAll("[_-]", " ");
        title = title.replaceAll("\\s+", " ");
        
        return title.trim();
    }
    
    /**
     * 判断是否为PDF文件
     */
    private boolean isPdfFile(MultipartFile file) {
        String contentType = file.getContentType();
        String filename = file.getOriginalFilename();
        
        return ("application/pdf".equals(contentType)) || 
               (filename != null && filename.toLowerCase().endsWith(".pdf"));
    }
}